﻿using System;
using System.Web;
using Castle.MonoRail.Framework;

namespace eduSrc.Web
{
    public class CacheFilterAttribute : IFilter
    {
        /// <summary>
        /// Gets or sets the cache duration in seconds. The default is 10 seconds
        /// </summary>
        /// <value>The cache duration in seconds.</value>
        public int Duration
        {
            get;
            set;
        }

        public CacheFilterAttribute()
        {
            Duration = 10;
        }

        #region IFilter 成员

        bool IFilter.Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
        {
            if (Duration <= 0) return false;

            HttpCachePolicy cachePolicy = context.Response.CachePolicy;   
            TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);

            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.SetExpires(DateTime.Now.Add(cacheDuration));
            cachePolicy.SetMaxAge(cacheDuration);
            cachePolicy.AppendCacheExtension("must-revalidate, proxy-revalidate");

            return true; 
        }

        #endregion
    }
}